package com.ks.listener;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ks.entity.User;

import common.Var;

@WebListener
public class UserSessionListener implements HttpSessionListener {
	private static Logger log = LoggerFactory.getLogger(UserSessionListener.class);

	/** 该HashMap以用户名-HttpSession对象存储一个账号只能被一个人登陆的信息。 */
	public static Map<String, HttpSession> sessionMap = new HashMap<>();

	public void sessionCreated(HttpSessionEvent se) {
		log.debug("==============================UserSessionListener初始化");
		HttpSession session = se.getSession();
		ServletContext sc = se.getSession().getServletContext();
		Integer totalcount = (Integer) sc.getAttribute(Var.TOTAL_COUNT);
		Integer accesscount = (Integer) sc.getAttribute(Var.ACCESS_COUNT);
		sc.setAttribute(Var.TOTAL_COUNT, totalcount + 1);
		sc.setAttribute(Var.ACCESS_COUNT, accesscount + 1);
		log.debug("Session【{}】被创建,当前在线人数：【{}】,总访问人数：【{}】", session.getId(), (Integer) sc.getAttribute(Var.ACCESS_COUNT),
				(Integer) sc.getAttribute(Var.TOTAL_COUNT));
	}

	public void sessionDestroyed(HttpSessionEvent se) {
		log.debug("===============================UserSessionListener被销毁");
		HttpSession session = se.getSession();
		ServletContext sc = se.getSession().getServletContext();
		Integer accesscount = (Integer) sc.getAttribute(Var.ACCESS_COUNT);
		if (accesscount <= 0) {
			sc.setAttribute(Var.ACCESS_COUNT, 0);
		} else {
			sc.setAttribute(Var.ACCESS_COUNT, accesscount - 1);
		}
		log.debug("Session【{}】被销毁,当前在线人数：【{}】,总访问人数：【{}】", session.getId(), (Integer) sc.getAttribute(Var.ACCESS_COUNT),
				(Integer) sc.getAttribute(Var.TOTAL_COUNT));
		/** 单一登录Session销毁后需要删除变量中的值，！！测试发现这里不用执行也可以 */
		delSession(session);
	}

	/** LoginServlet中判断如果是新创建的Session会话，就把上一个会话session的清空，这里判断一下是否清空没有清空继续清空 */
	private synchronized void delSession(HttpSession session) {
		// 删除单一登录中记录的变量
		if (session != null && session.getAttribute(Var.USER_INFO) != null) {
			User user = (User) session.getAttribute(Var.USER_INFO);
			UserSessionListener.sessionMap.remove(user.getUsername());
		}
	}

}
